package org.hugh.space.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hugh.space.business.CurrentUser;
import org.hugh.space.entity.FileEntity;
import org.hugh.space.utils.StreamUtil;








public class FileUploadServlet extends BaseSpringServlet{
	
	private static final long MAX_SIZE = 10000000;
	private static final String PARSE_REQUEST_ERROR = "Parse request error";
	private static final String TEXT_MESSAGE = "::%s::%s::";
	private static final Log log = LogFactory
	.getLog(FileUploadServlet.class);
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		
		HttpSession session = request.getSession(true);
		ServletFileUpload upload = new ServletFileUpload();
		upload.setFileSizeMax(MAX_SIZE);
		upload.setHeaderEncoding("UTF-8");
		String message = null;
		Map<String, String> parameters = new HashMap<String, String>();

		try {
			FileItemIterator iter;
			try {
				iter = upload.getItemIterator(request);
				FileItemStream imageFileItem = null;
				String folder = null;
				InputStream stream = null;
				InputStream filestream = null;
				byte[] fileData = null;
				
				while (iter.hasNext()) {
					FileItemStream item = iter.next();
					stream = item.openStream();
					if (item.isFormField()) {
						parameters.put(item.getFieldName(), 
								Streams.asString(stream, "UTF-8"));
					} else {
						imageFileItem = item;
						fileData = StreamUtil.readFileStream(stream);
					}
				}
				message = processFile(imageFileItem, fileData, parameters);
//				request.getRequestDispatcher("/fileList").forward(request, response);
				response.sendRedirect("/fileList");
			} catch (FileUploadException e) {
				log.error(PARSE_REQUEST_ERROR);
				throw new UploadException(PARSE_REQUEST_ERROR);
			}
		} catch (UploadException e) {
			message = createMessage("error", e.getMessage()); 
			log.error(message);
		}
	}
	
	private String createMessage(final String result, final String message) {
		return String.format(TEXT_MESSAGE, result, message);
	}
	
	private String processFile(FileItemStream fileItem, byte[] data, 
			Map<String, String> parameters) throws UploadException {
		
		return processResourceFileJSON(fileItem, data);
	}
	
	private String processResourceFileJSON(FileItemStream item, byte[] data) throws UploadException {
		FileEntity file = processResourceFile(item, data);
		String message = createMessage("success", file.getId());
		return message;
	}
	
	private FileEntity processResourceFile(FileItemStream item, byte[] data) throws UploadException {

		String path = item.getName();
		String filename = FilenameUtils.getName(path);
		FileEntity	file = new FileEntity();
		file.setFilename(filename);
		file.setLastModifiedTime(new Date());
		file.setSize(data.length);
		file.setMimeType(MimeType.getContentTypeByExt(getFileExt(file.getFilename())));
		file.setUser(CurrentUser.getInstance().getId()+"");
		getDao().getFileDao().save(file, data);
		return file;
	}
	
	private String getFileExt(final String path) {
		int s = path.lastIndexOf(".");
		return path.substring(s + 1, path.length()).toLowerCase();
	}
	
	
}
